from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import desc

from backend.infrastructure.database import db
from backend.models.notification import Notification, NotificationSetting
from backend.models.user import User
from backend.services.notification_service import NotificationService
from backend.services.unified_log_service import UnifiedLogService
from . import miniprogram_bp

log_service = UnifiedLogService()


@miniprogram_bp.route('/notifications', methods=['GET'])
@jwt_required()
def get_notifications():
    """获取用户通知列表"""
    try:
        current_user_id = get_jwt_identity()
        
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        status = request.args.get('status')  # unread, read, all
        
        # 获取通知列表
        result = NotificationService.get_user_notifications(
            user_id=current_user_id,
            page=page,
            per_page=per_page,
            status=status
        )
        
        return jsonify({
            'success': True,
            'data': result
        })
        
    except Exception as e:
        current_app.logger.error(f'获取通知列表失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取通知列表失败'}), 500


@miniprogram_bp.route('/notifications/unread-count', methods=['GET'])
@jwt_required()
def get_unread_count():
    """获取未读通知数量"""
    try:
        current_user_id = get_jwt_identity()
        
        count = NotificationService.get_unread_count(current_user_id)
        
        return jsonify({
            'success': True,
            'data': {'unread_count': count}
        })
        
    except Exception as e:
        current_app.logger.error(f'获取未读通知数量失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取未读通知数量失败'}), 500


@miniprogram_bp.route('/notifications/<int:notification_id>/read', methods=['POST'])
@jwt_required()
def mark_as_read(notification_id):
    """标记通知为已读"""
    try:
        current_user_id = get_jwt_identity()
        
        success = NotificationService.mark_as_read(notification_id, current_user_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': '标记已读成功'
            })
        else:
            return jsonify({
                'success': False,
                'message': '通知不存在或无权限'
            }), 404
        
    except Exception as e:
        current_app.logger.error(f'标记通知已读失败: {str(e)}')
        return jsonify({'success': False, 'message': '标记已读失败'}), 500


@miniprogram_bp.route('/notifications/read-all', methods=['POST'])
@jwt_required()
def mark_all_as_read():
    """标记所有通知为已读"""
    try:
        current_user_id = get_jwt_identity()
        
        # 获取所有未读通知
        unread_notifications = Notification.query.filter(
            Notification.user_id == current_user_id,
            Notification.status == 'unread'
        ).all()
        
        # 批量标记为已读
        for notification in unread_notifications:
            notification.status = 'read'
            notification.read_at = db.func.now()
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='notifications',
            record_id=None,
            details=f'批量标记{len(unread_notifications)}条通知为已读'
        )
        
        return jsonify({
            'success': True,
            'message': f'已标记{len(unread_notifications)}条通知为已读'
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'批量标记已读失败: {str(e)}')
        return jsonify({'success': False, 'message': '批量标记已读失败'}), 500


@miniprogram_bp.route('/notifications/settings', methods=['GET'])
@jwt_required()
def get_notification_settings():
    """获取通知设置"""
    try:
        current_user_id = get_jwt_identity()
        
        settings = NotificationSetting.query.filter(
            NotificationSetting.user_id == current_user_id
        ).all()
        
        return jsonify({
            'success': True,
            'data': [setting.to_dict() for setting in settings]
        })
        
    except Exception as e:
        current_app.logger.error(f'获取通知设置失败: {str(e)}')
        return jsonify({'success': False, 'message': '获取通知设置失败'}), 500


@miniprogram_bp.route('/notifications/settings', methods=['POST'])
@jwt_required()
def update_notification_settings():
    """更新通知设置"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        if not data or 'settings' not in data:
            return jsonify({'success': False, 'message': '缺少设置数据'}), 400
        
        success_count = 0
        for setting_data in data['settings']:
            if all(key in setting_data for key in ['notification_type', 'enabled', 'wechat_enabled', 'app_enabled']):
                # 更新或创建设置
                setting = NotificationSetting.query.filter(
                    NotificationSetting.user_id == current_user_id,
                    NotificationSetting.notification_type == setting_data['notification_type']
                ).first()
                
                if setting:
                    setting.enabled = setting_data['enabled']
                    setting.wechat_enabled = setting_data['wechat_enabled']
                    setting.app_enabled = setting_data['app_enabled']
                else:
                    setting = NotificationSetting(
                        user_id=current_user_id,
                        notification_type=setting_data['notification_type'],
                        enabled=setting_data['enabled'],
                        wechat_enabled=setting_data['wechat_enabled'],
                        app_enabled=setting_data['app_enabled']
                    )
                    db.session.add(setting)
                
                success_count += 1
        
        db.session.commit()
        
        # 记录操作日志
        log_service.log_operation(
            user_id=current_user_id,
            action='UPDATE',
            table_name='notification_settings',
            record_id=None,
            details=f'更新{success_count}项通知设置'
        )
        
        return jsonify({
            'success': True,
            'message': f'成功更新{success_count}项设置'
        })
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'更新通知设置失败: {str(e)}')
        return jsonify({'success': False, 'message': '更新通知设置失败'}), 500


@miniprogram_bp.route('/notifications/test', methods=['POST'])
@jwt_required()
def send_test_notification():
    """发送测试通知"""
    try:
        current_user_id = get_jwt_identity()
        data = request.get_json()
        
        notification_type = data.get('notification_type', 'system')
        title = data.get('title', '测试通知')
        content = data.get('content', '这是一条测试通知')
        
        # 创建测试通知
        notification = NotificationService.create_notification(
            user_id=current_user_id,
            title=title,
            content=content,
            notification_type=notification_type,
            priority='normal',
            send_wechat=True
        )
        
        if notification:
            return jsonify({
                'success': True,
                'message': '测试通知发送成功',
                'data': notification.to_dict()
            })
        else:
            return jsonify({
                'success': False,
                'message': '测试通知发送失败'
            }), 500
        
    except Exception as e:
        current_app.logger.error(f'发送测试通知失败: {str(e)}')
        return jsonify({'success': False, 'message': '发送测试通知失败'}), 500 